<template>
  <div class="page-container">
    <button class="back-button" @click="goToHome">
      <span class="icon-arrow-left"></span>
      返回首页
    </button>
    
    <div class="header-actions">
      <h1>设备维护</h1>
      <button class="primary-btn" @click="showAddMaintenanceModal = true">
        <span class="icon-plus"></span> 新增维护记录
      </button>
    </div>
    
    <p>这里是设备维护页面，您可以安排和管理设备的维护计划。</p>
    
    <div class="card">
      <div class="search-filter">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索设备或维护类型..." 
          class="search-input"
        >
        <select v-model="filterStatus" class="filter-select">
          <option value="">所有状态</option>
          <option value="计划中">计划中</option>
          <option value="进行中">进行中</option>
          <option value="已完成">已完成</option>
          <option value="已取消">已取消</option>
        </select>
      </div>
      
      <table class="maintenance-table">
        <thead>
          <tr>
            <th>维护编号</th>
            <th>设备名称</th>
            <th>设备编号</th>
            <th>维护类型</th>
            <th>计划日期</th>
            <th>实际日期</th>
            <th>负责人</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="maintenance in filteredMaintenances" :key="maintenance.id" class="table-row">
            <td>{{ maintenance.code }}</td>
            <td>{{ maintenance.deviceName }}</td>
            <td>{{ maintenance.deviceCode }}</td>
            <td>{{ maintenance.type }}</td>
            <td>{{ maintenance.scheduledDate }}</td>
            <td>{{ maintenance.actualDate || '-' }}</td>
            <td>{{ maintenance.manager }}</td>
            <td>
              <span :class="`status-badge ${maintenance.statusClass}`">
                {{ maintenance.status }}
              </span>
            </td>
            <td class="action-buttons">
              <button 
                class="btn-start" 
                @click="startMaintenance(maintenance)"
                v-if="maintenance.status === '计划中'"
              >
                开始
              </button>
              <button 
                class="btn-complete" 
                @click="completeMaintenance(maintenance)"
                v-if="maintenance.status === '进行中'"
              >
                完成
              </button>
              <button 
                class="btn-cancel" 
                @click="cancelMaintenance(maintenance)"
                v-if="['计划中', '进行中'].includes(maintenance.status)"
              >
                取消
              </button>
              <button class="btn-view" @click="viewMaintenance(maintenance)">详情</button>
            </td>
          </tr>
          <tr v-if="filteredMaintenances.length === 0">
            <td colspan="9" class="no-data">暂无维护记录</td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @click="currentPage--"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @click="currentPage++"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 新增维护记录弹窗 -->
    <div v-if="showAddMaintenanceModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>新增维护记录</h3>
          <button class="close-btn" @click="showAddMaintenanceModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form class="maintenance-form">
            <div class="form-group">
              <label>选择设备 <span class="required">*</span></label>
              <select v-model="currentMaintenance.deviceId" required @change="updateDeviceInfo">
                <option value="">-- 请选择设备 --</option>
                <option 
                  v-for="device in devices" 
                  :key="device.id" 
                  :value="device.id"
                >
                  {{ device.name }} ({{ device.code }})
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>维护类型 <span class="required">*</span></label>
              <select v-model="currentMaintenance.type" required>
                <option value="">-- 请选择维护类型 --</option>
                <option value="日常保养">日常保养</option>
                <option value="故障维修">故障维修</option>
                <option value="定期检修">定期检修</option>
                <option value="部件更换">部件更换</option>
              </select>
            </div>
            <div class="form-group">
              <label>计划日期 <span class="required">*</span></label>
              <input type="date" v-model="currentMaintenance.scheduledDate" required>
            </div>
            <div class="form-group">
              <label>维护负责人 <span class="required">*</span></label>
              <select v-model="currentMaintenance.managerId" required>
                <option value="">-- 请选择负责人 --</option>
                <option 
                  v-for="user in users" 
                  :key="user.id" 
                  :value="user.id"
                >
                  {{ user.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>维护内容</label>
              <textarea 
                v-model="currentMaintenance.content" 
                rows="3"
                placeholder="请输入维护内容..."
              ></textarea>
            </div>
            <div class="form-group">
              <label>预计费用</label>
              <input 
                type="number" 
                v-model="currentMaintenance.estimatedCost" 
                placeholder="0.00"
                step="0.01"
                min="0"
              >
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAddMaintenanceModal = false">取消</button>
          <button class="save-btn" @click="saveMaintenance">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DeviceMaintenance',
  data() {
    return {
      searchQuery: '',
      filterStatus: '',
      currentPage: 1,
      pageSize: 10,
      showAddMaintenanceModal: false,
      currentMaintenance: {
        deviceId: '',
        type: '',
        scheduledDate: new Date().toISOString().split('T')[0],
        managerId: '',
        content: '',
        estimatedCost: 0
      },
      // 设备数据
      devices: [
        { id: 1, code: 'DEV-001', name: '笔记本电脑', model: 'ThinkPad X1', status: '正常' },
        { id: 2, code: 'DEV-002', name: '打印机', model: 'HP LaserJet Pro', status: '维修中' },
        { id: 3, code: 'DEV-003', name: '投影仪', model: 'Epson CB-X06', status: '正常' },
        { id: 4, code: 'DEV-004', name: '扫描仪', model: 'Canon DR-C225', status: '已报废' },
      ],
      // 维护人员
      users: [
        { id: 1, name: '张三', department: '设备部' },
        { id: 2, name: '李四', department: '设备部' },
        { id: 3, name: '王五', department: 'IT部' },
      ],
      // 维护记录
      maintenances: [
        { 
          id: 1, 
          code: 'MNT-001', 
          deviceId: 2,
          deviceName: '打印机',
          deviceCode: 'DEV-002',
          type: '故障维修',
          scheduledDate: '2023-05-15',
          actualDate: '2023-05-15',
          managerId: 1,
          manager: '张三',
          content: '更换墨盒和维修卡纸问题',
          estimatedCost: 200,
          actualCost: 220,
          status: '进行中',
          statusClass: 'status-in-progress'
        },
        { 
          id: 2, 
          code: 'MNT-002', 
          deviceId: 1,
          deviceName: '笔记本电脑',
          deviceCode: 'DEV-001',
          type: '定期检修',
          scheduledDate: '2023-06-10',
          actualDate: '',
          managerId: 3,
          manager: '王五',
          content: '系统更新和硬件检查',
          estimatedCost: 0,
          actualCost: 0,
          status: '计划中',
          statusClass: 'status-planned'
        },
        { 
          id: 3, 
          code: 'MNT-003', 
          deviceId: 3,
          deviceName: '投影仪',
          deviceCode: 'DEV-003',
          type: '日常保养',
          scheduledDate: '2023-05-01',
          actualDate: '2023-05-01',
          managerId: 2,
          manager: '李四',
          content: '清洁镜头和检查灯泡寿命',
          estimatedCost: 0,
          actualCost: 0,
          status: '已完成',
          statusClass: 'status-completed'
        }
      ]
    };
  },
  computed: {
    filteredMaintenances() {
      return this.maintenances
        .filter(maintenance => 
          (this.searchQuery === '' || 
           maintenance.deviceName.includes(this.searchQuery) || 
           maintenance.deviceCode.includes(this.searchQuery) ||
           maintenance.type.includes(this.searchQuery)) &&
          (this.filterStatus === '' || maintenance.status === this.filterStatus)
        )
        .slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
        );
    },
    totalPages() {
      const filteredCount = this.maintenances.filter(maintenance => 
        (this.searchQuery === '' || 
         maintenance.deviceName.includes(this.searchQuery) || 
         maintenance.deviceCode.includes(this.searchQuery) ||
         maintenance.type.includes(this.searchQuery)) &&
        (this.filterStatus === '' || maintenance.status === this.filterStatus)
      ).length;
      return Math.ceil(filteredCount / this.pageSize);
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    updateDeviceInfo() {
      const device = this.devices.find(d => d.id === this.currentMaintenance.deviceId);
      if (device) {
        this.currentMaintenance.deviceName = device.name;
        this.currentMaintenance.deviceCode = device.code;
      }
    },
    saveMaintenance() {
      // 验证必填项
      if (!this.currentMaintenance.deviceId || !this.currentMaintenance.type || 
          !this.currentMaintenance.scheduledDate || !this.currentMaintenance.managerId) {
        alert('请填写必填项');
        return;
      }
      
      // 获取负责人姓名
      const manager = this.users.find(u => u.id === this.currentMaintenance.managerId);
      
      // 创建新维护记录
      const newMaintenance = {
        id: this.maintenances.length + 1,
        code: `MNT-${(this.maintenances.length + 1).toString().padStart(3, '0')}`,
        ...this.currentMaintenance,
        manager: manager ? manager.name : '',
        actualDate: '',
        actualCost: 0,
        status: '计划中',
        statusClass: 'status-planned'
      };
      
      this.maintenances.unshift(newMaintenance);
      
      // 重置表单并关闭弹窗
      this.resetMaintenanceForm();
      this.showAddMaintenanceModal = false;
    },
    resetMaintenanceForm() {
      this.currentMaintenance = {
        deviceId: '',
        type: '',
        scheduledDate: new Date().toISOString().split('T')[0],
        managerId: '',
        content: '',
        estimatedCost: 0
      };
    },
    startMaintenance(maintenance) {
      const index = this.maintenances.findIndex(m => m.id === maintenance.id);
      if (index !== -1) {
        this.maintenances[index].status = '进行中';
        this.maintenances[index].statusClass = 'status-in-progress';
      }
    },
    completeMaintenance(maintenance) {
      const index = this.maintenances.findIndex(m => m.id === maintenance.id);
      if (index !== -1) {
        this.maintenances[index].status = '已完成';
        this.maintenances[index].statusClass = 'status-completed';
        this.maintenances[index].actualDate = new Date().toISOString().split('T')[0];
        // 可以在这里弹出输入实际费用的对话框
      }
    },
    cancelMaintenance(maintenance) {
      const confirmCancel = confirm(`确定要取消 ${maintenance.deviceName} 的维护计划吗？`);
      if (confirmCancel) {
        const index = this.maintenances.findIndex(m => m.id === maintenance.id);
        if (index !== -1) {
          this.maintenances[index].status = '已取消';
          this.maintenances[index].statusClass = 'status-canceled';
        }
      }
    },
    viewMaintenance(maintenance) {
      console.log('查看维护详情:', maintenance);
      // 可以实现查看详情的逻辑
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.primary-btn {
  background: #2ecc71;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.3s;
}

.primary-btn:hover {
  background: #27ae60;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.search-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input, .filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
  max-width: 300px;
}

.maintenance-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.maintenance-table th, .maintenance-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.maintenance-table th {
  background: #f8f9fa;
  font-weight: 600;
}

.table-row:hover {
  background: #f9f9f9;
  transition: background 0.2s;
}

.status-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-planned {
  background: #e8f4fd;
  color: #3498db;
}

.status-in-progress {
  background: #fff3e0;
  color: #f57c00;
}

.status-completed {
  background: #eafaf1;
  color: #27ae60;
}

.status-canceled {
  background: #fdedeb;
  color: #e74c3c;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-view, .btn-start, .btn-complete, .btn-cancel {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
}

.btn-view {
  background: #e3f2fd;
  color: #1976d2;
}

.btn-start {
  background: #e8f5e9;
  color: #43a047;
}

.btn-complete {
  background: #e0f7fa;
  color: #00acc1;
}

.btn-cancel {
  background: #ffebee;
  color: #c62828;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.maintenance-form {
  display: grid;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #e74c3c;
}

.form-group input, 
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group textarea {
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .save-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.save-btn {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.cancel-btn:hover {
  background: #f5f5f5;
}

.save-btn:hover {
  background: #2980b9;
}

/* 继承并复用返回按钮样式 */
.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}
</style>